<?php
/**
 * 所有方法写在此文件，自创SDK
 */

namespace App\Http\Controllers\WeChatService;

use Illuminate\Support\Facades\Redis;

class WeChatServiceSDK
{
    // 获取access_token,存入Redis
    public static function GetAccesssToken() {
        try {
            $appID = WeChatConfig::appID;
            $secret = WeChatConfig::appSecret;
            $getUrl = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid='.$appID.'&secret='.$secret;
            $data = json_decode(file_get_contents($getUrl), true);
            $accessToken = $data['access_token'];
            $valueTime = $data['expires_in'];
            Redis::setex('accessToken', $valueTime, $accessToken);
            return $accessToken;
        } catch (\Throwable $th) {
            return false;
        }
    }

    // 判断redis里的accessToken是否过期，没过期取出，过期则重新生成
    public static function GetAccessTokenFromRedis() {
        $accessToken = Redis::get('accessToken');
        if ($accessToken) {
            return $accessToken;
        } else {
            return self::GetAccesssToken();
        }
    }

    // 获取用户基本信息接口
    public static function GetUserMessage($access_token, $open_id) {
        $getUrl = 'https://api.weixin.qq.com/cgi-bin/user/info?access_token='.$access_token.'&openid='.$open_id.'&lang=zh_CN';
        return json_decode(file_get_contents($getUrl), true);
    }

    // 发送模板消息
    public static function SendModelMessage($postData) {
        $access_token = WeChatServiceSDK::GetAccessTokenFromRedis();
        if ($access_token) {
            $postUrl = 'https://api.weixin.qq.com/cgi-bin/message/template/send?access_token='.$access_token;
            return json_decode(WeChatServiceSDK::post($postData, $postUrl), true);
        } else {
            return ['code'=>'400'];
        }
    }

    // post请求
    public static function post($post_data, $url)
    {
        $curl = curl_init();
        $curlPost = json_encode($post_data);
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_HEADER, false);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_NOBODY, true);
        curl_setopt($curl, CURLOPT_POST, true);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $curlPost);
        $return_str = curl_exec($curl);
        curl_close($curl);
        return $return_str;
    }
}
